#!/bin/bash
set -e
set -x
MYDIR="${0%/*}"
cd "$MYDIR/.."
source "recipes/common.sh"


# RECIPE START linux
# depends: kmod-native

save_CFLAGS="$CFLAGS"
save_CPPFLAGS="$CPPFLAGS"
save_LDFLAGS="$LDFLAGS"
unset CFLAGS
unset CPPFLAGS
unset LDFLAGS

KBUILD_OUTPUT="/tmp/build/$LINUX_ARCH"
COMMON_ENV="KBUILD_OUTPUT=${KBUILD_OUTPUT} WERROR=0 KBUILD_BUILD_TIMESTAMP='2018-01-31T19:05:00+04:00' DISTCC_BACKOFF_PERIOD=0 DISTCC_FALLBACK=0"
SRCDIR="`pwd`/linux-${LINUX_SUBREPO}"
EXTRA_CONFIGS=''

rm -rf "$KBUILD_OUTPUT"
mkdir -p "$KBUILD_OUTPUT"

if test -f ${SRCDIR}/.gitrepo; then
	CONFIG_LOCALVERSION=$(awk '/commit = / { print $3 }' <${SRCDIR}/.gitrepo)
	extra_cfg="${KBUILD_OUTPUT}/subrepo-version.config"
	cat > "${extra_cfg}" <<-EOF
	CONFIG_LOCALVERSION="-${CONFIG_LOCALVERSION}"
	# CONFIG_LOCALVERSION_AUTO is not set
	EOF
	EXTRA_CONFIGS="${EXTRA_CONFIGS}${EXTRA_CONFIGS+ }${extra_cfg}"
fi

# make a .config
${SRCDIR}/scripts/kconfig/merge_config.sh -m -O "${KBUILD_OUTPUT}" \
	"${SRCDIR}/arch/${LINUX_ARCH}/configs/${LINUX_DEFCONFIG}" \
	"${SRCDIR}/config.local" \
	${EXTRA_CONFIGS}

env $COMMON_ENV make -j${JOBS} -C ${SRCDIR} \
	ARCH=$LINUX_ARCH \
	CROSS_COMPILE="${TARGET}-" \
	oldconfig </dev/null

env $COMMON_ENV make -j${JOBS} -C ${SRCDIR} \
	ARCH=$LINUX_ARCH \
	CROSS_COMPILE="${TARGET}-" \
	all


env $COMMON_ENV make -j${JOBS} -C "${SRCDIR}" \
	ARCH=$LINUX_ARCH \
	CROSS_COMPILE="${TARGET}-" \
	INSTALL_PATH="$stage/boot" \
	INSTALL_MOD_PATH="${stage}${prefix}" \
	install modules_install

kversion=`cat ${KBUILD_OUTPUT}/include/config/kernel.release`

env $COMMON_ENV \
	depmod -b "${stage}${prefix}" $kversion

export CFLAGS="$save_CFLAGS"
export CPPFLAGS="$save_CPPFLAGS"
export LDFLAGS="$save_LDFLAGS"

# RECIPE END linux
